/**
 * Created by xinxinran on 2018/7/18.
 */
'use strict';
import api from '../api'

const jsSignedUrlCache = {};
const WeChat = {};
window['ENV_DEF_WECHAT_APP_ID'] = 1;
const appId = ENV_DEF_WECHAT_APP_ID;
const wx = window['wx'];

WeChat.appId = appId;

WeChat.config = function (jsApiList) {
    let url = window.location.href;
    return new Promise((resolve, reject) => {
        // 缓存js签名
        let needSignJsApi = jsApiList.filter(jsApi => !(jsSignedUrlCache[url] && jsSignedUrlCache[url][jsApi])),
            debugRes;
        if (!needSignJsApi.length) {
            resolve(true);
        } else {
            api.weChat.signJsApiBySHA({url, appId})
                .then(function (res) {
                    console.log('签名结果：{}', JSON.stringify(res));
                    let data = res.data;
                    wx.config(debugRes = {
                        // debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                        appId: data.appId, // 必填，公众号的唯一标识
                        timestamp: data.timestamp, // 必填，生成签名的时间戳
                        nonceStr: data.nonceStr, // 必填，生成签名的随机串
                        signature: data.signature, // 必填，签名，见附录1
                        jsApiList: needSignJsApi || [] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                    });
                    wx.ready(function () {
                        needSignJsApi.forEach(jsApi => {
                            (jsSignedUrlCache[url] || (jsSignedUrlCache[url] = {}))[jsApi] = true;
                        }); // 缓存签名
                        setTimeout(() => {
                            resolve(true);
                        }, 200);    // 确保微信能够调用，延后200ms处理
                    });
                    wx.error(function (e) {
                        reject({code: 'ERROR', msg: '微信签名错误', weixinError: e});
                    })
                })
                .catch(error => {
                    reject({code: 'FAIL', msg: '微信签名失败', weixinError: error})
                });
        }
    });
};

WeChat.chooseImage = function () {
    return WeChat.config(['chooseImage'])
        .then(() => {
            return new Promise((resolve, reject) => {
                wx.chooseImage({
                    count: 1, // 默认9
                    sizeType: ['original'], // 可以指定是原图还是压缩图，默认二者都有
                    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                    success: function (res) {
                        resolve(res);
                    },
                    fail: function (res) {
                        reject({code: 'ERROR', msg: res});
                    }
                });
            })
        }).catch(e => {
            console.log(e);
        });
};

WeChat.uploadImage = function ({localId, isShowProgressTips = 1}) {
    return WeChat.config(['uploadImage'])
        .then(() => {
            return new Promise((resolve, reject) => {
                (localId || (reject('上传照片必须指定chooseImage的localId') && false)) && setTimeout(() => {
                    wx.uploadImage({
                        localId: localId, // 需要上传的图片的本地ID，由chooseImage接口获得,外部必须传入
                        isShowProgressTips: isShowProgressTips, // 默认为1，显示进度提示
                        success: function (res) {
                            resolve(res);
                        },
                        fail: function (res) {
                            reject(res);
                        }
                    })
                }, 100);
            });
        })
};

export {WeChat as default, WeChat}
